/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Vista;

import Controlador.ControlCliente;
import Controlador.ControlImagen;
import Modelo.Cotizacion;
import Modelo.Imagen;
import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.swing.JOptionPane;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.export.ooxml.JRDocxExporter;
import net.sf.jasperreports.engine.util.JRLoader;

/**
 *
 * @author Damián
 */
public class PnlPrevisualizar extends javax.swing.JPanel {

    /**
     * Creates new form PnlPrevisualizar
     */
    Cotizacion cotActual;
    String ruta = "preview0.pdf";
    String ruta1 = "preview1.pdf";
    int aux = 0;
    int paginas;
    int pagina;

    public PnlPrevisualizar(Cotizacion cotActual) {
        initComponents();
        this.cotActual = cotActual;
        //pre();
    }

    public void generar(Cotizacion cotActual) {
        this.cotActual = cotActual;
        pre();
    }

    public void pre() {
        if (cotActual != null) {
            if (cotActual.getCodigo() > 0) {
                Runnable hilo = new Runnable() {

                    @Override
                    public void run() {
                        lblEspera.setText("Generando la previsualización.");
                        lblEspera.setBusy(true);
                        try {
                            Connection cn = new ControlCliente().conectar();
                            HashMap<String, Object> params = new HashMap<>();
                            params.put("codigo_cotizacion", cotActual.getCodigo());
                            guardarImg();
                            //entregar();

                            System.out.println("Exportando cotización a " + ruta);
                            Boolean isPDF = true;

                            jasperReport(ruta, params, cn, true);
                            lblEspera.setBusy(false);

                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                        preview(aux == 0 ? ruta : ruta1, 1);
                        System.out.println("acabo el hilo");
                    }
                };
                Thread h = new Thread(hilo);
                h.start();
            } else {
                JOptionPane.showMessageDialog(this, "Cotización Inválida");
                System.out.println("Codigo de contizacion invalido");
            }
        } else {
            JOptionPane.showMessageDialog(this, "Cotización Inválida.");
            System.out.println("cotizacion nula");
        }
    }

    public boolean jasperReport(String ruta, Map<String, Object> params, Connection conn, boolean pdf) throws ClassNotFoundException, JRException {
        try {

            JasperReport report = (JasperReport) JRLoader.loadObject(new File("report1.jasper"));
            JasperPrint jasperPrint = JasperFillManager.fillReport(report, params, conn);
            if (pdf) {
                JRExporter exporter = new JRPdfExporter();
                exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
                exporter.setParameter(JRExporterParameter.OUTPUT_FILE, new java.io.File(ruta));
                exporter.exportReport();

            } else {
                JRDocxExporter exp = new JRDocxExporter();
                exp.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
                exp.setParameter(JRExporterParameter.OUTPUT_FILE, new java.io.File(ruta));
                exp.exportReport();
            }

        } catch (Exception e) {
            //e.printStackTrace();
            if (aux == 0) {
                System.out.println("Error con la ruta0, cambiando a ruta 1");
                jasperReport(ruta1, params, conn, pdf);
                aux = 1;
            } else if (aux == 1) {
                System.out.println("Error con la ruta, cambiando a ruta 0");
                jasperReport(ruta, params, conn, pdf);
                aux = 0;
            }
        }
        return true;
    }

    public static BufferedImage toBufferedImage(Image img) {
        int width = img.getWidth(null);
        int height = img.getHeight(null);
        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TRANSLUCENT);
        Graphics g = bi.getGraphics();
        g.drawImage(img, 0, 0, null);
        g.dispose();
        return bi;
    }

    public void guardarImg() {
        try {
            if (new File("./img").isDirectory() == false) {

            }
            ArrayList<Imagen> listaImg = new ControlImagen().getImagenes();
            for (int i = 0; i < listaImg.size(); i++) {
                Imagen imagen = listaImg.get(i);
                String formato = imagen.getNombre().substring(imagen.getNombre().length() - 3);
                File archivo = new File("./img/" + imagen.getNombre());

                System.out.println(archivo.createNewFile());
                ImageIO.write(toBufferedImage(imagen.getImagen()),
                        formato, archivo);
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void preview(String fileD, int pag) {
        try {

            //load a pdf from a byte buffer
            File file = new File(fileD);
            RandomAccessFile raf = new RandomAccessFile(file, "r");
            FileChannel channel = raf.getChannel();
            ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY,
                    0, channel.size());
            PDFFile pdffile = new PDFFile(buf);
            PDFPage page = pdffile.getPage(pag);
            paginas = pdffile.getNumPages();
            panel.showPage(page);
            channel.close();
            raf.close();
            buf.clear();
            pagina = pag;
            System.out.println("Mostrando la página "+pagina+" de "+paginas);
            if (pagina == 0 || pagina == 1) {
                btnAnterior.setEnabled(false);
            } else {
                btnAnterior.setEnabled(true);

            }
            if (pagina==paginas) {
                btnSiguiente.setEnabled(false);
            } else {
                btnSiguiente.setEnabled(true);
            }
            //panel.useZoomTool(true);
            //panel.setClip(new Rectangle(100,100));
            //panel.setPreferredSize(screenSize);
        } catch (IOException iOException) {
            iOException.printStackTrace();
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jXStatusBar1 = new org.jdesktop.swingx.JXStatusBar();
        lblEspera = new org.jdesktop.swingx.JXBusyLabel();
        btnAnterior = new org.jdesktop.swingx.JXButton();
        btnSiguiente = new org.jdesktop.swingx.JXButton();
        btnZoom_aumentar = new org.jdesktop.swingx.JXButton();
        btnZoom_reducir = new org.jdesktop.swingx.JXButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        panel = new com.sun.pdfview.PagePanel();

        setLayout(new java.awt.BorderLayout());

        lblEspera.setText("Esperando...");
        jXStatusBar1.add(lblEspera);

        btnAnterior.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Vista/Iconos/go-previous.png"))); // NOI18N
        btnAnterior.setToolTipText("Página Anterior");
        btnAnterior.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAnteriorActionPerformed(evt);
            }
        });
        jXStatusBar1.add(btnAnterior);

        btnSiguiente.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Vista/Iconos/go-next.png"))); // NOI18N
        btnSiguiente.setToolTipText("Página Siguiente");
        btnSiguiente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSiguienteActionPerformed(evt);
            }
        });
        jXStatusBar1.add(btnSiguiente);

        btnZoom_aumentar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Vista/Iconos/zoom-in.png"))); // NOI18N
        btnZoom_aumentar.setToolTipText("Aumentar Zoom");
        btnZoom_aumentar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnZoom_aumentarActionPerformed(evt);
            }
        });
        jXStatusBar1.add(btnZoom_aumentar);

        btnZoom_reducir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Vista/Iconos/zoom-out.png"))); // NOI18N
        btnZoom_reducir.setToolTipText("Reducir Zoom");
        btnZoom_reducir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnZoom_reducirActionPerformed(evt);
            }
        });
        jXStatusBar1.add(btnZoom_reducir);

        add(jXStatusBar1, java.awt.BorderLayout.PAGE_START);

        javax.swing.GroupLayout panelLayout = new javax.swing.GroupLayout(panel);
        panel.setLayout(panelLayout);
        panelLayout.setHorizontalGroup(
            panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 800, Short.MAX_VALUE)
        );
        panelLayout.setVerticalGroup(
            panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 600, Short.MAX_VALUE)
        );

        jScrollPane1.setViewportView(panel);

        add(jScrollPane1, java.awt.BorderLayout.CENTER);
    }// </editor-fold>//GEN-END:initComponents

    private void btnSiguienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSiguienteActionPerformed
        preview(aux == 0 ? ruta : ruta1, pagina + 1);
    }//GEN-LAST:event_btnSiguienteActionPerformed

    private void btnZoom_aumentarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnZoom_aumentarActionPerformed
        panel.setPreferredSize(new Dimension(panel.getSize().width + 50, panel.getSize().height + 50));
        panel.setSize(new Dimension(panel.getSize().width + 50, panel.getSize().height + 50));
    }//GEN-LAST:event_btnZoom_aumentarActionPerformed

    private void btnZoom_reducirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnZoom_reducirActionPerformed
        panel.setPreferredSize(new Dimension(panel.getSize().width - 50, panel.getSize().height - 50));
        panel.setSize(new Dimension(panel.getSize().width - 50, panel.getSize().height - 50));
    }//GEN-LAST:event_btnZoom_reducirActionPerformed

    private void btnAnteriorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAnteriorActionPerformed
        preview(aux == 0 ? ruta : ruta1, pagina - 1);
    }//GEN-LAST:event_btnAnteriorActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private org.jdesktop.swingx.JXButton btnAnterior;
    private org.jdesktop.swingx.JXButton btnSiguiente;
    private org.jdesktop.swingx.JXButton btnZoom_aumentar;
    private org.jdesktop.swingx.JXButton btnZoom_reducir;
    private javax.swing.JScrollPane jScrollPane1;
    private org.jdesktop.swingx.JXStatusBar jXStatusBar1;
    private org.jdesktop.swingx.JXBusyLabel lblEspera;
    private com.sun.pdfview.PagePanel panel;
    // End of variables declaration//GEN-END:variables
}
